package v1

import (
	"github.com/gin-gonic/gin"
	"mall_2.0/pkg/utils/ctl"
	"mall_2.0/pkg/utils/log"
	"mall_2.0/service"
	"mall_2.0/types"
	"net/http"
)

// CreateAddressHandler 创建地址
func CreateAddressHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.AddressCreateReq
		if err := c.ShouldBind(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetAddressSrv()
		resp, err := l.AddressCreate(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}

// ShowAddressHandler 获取某个详细地址
func ShowAddressHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.AddressGetReq
		if err := c.ShouldBindUri(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetAddressSrv()
		resp, err := l.AddressShow(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}

// ListAddressHandler 获取地址列表
func ListAddressHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.AddressListReq
		if err := c.ShouldBind(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetAddressSrv()
		resp, err := l.AddressList(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}

// UpdateAddressHandler 更新地址
func UpdateAddressHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.AddressServiceReq
		if err := c.ShouldBindUri(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetAddressSrv()
		resp, err := l.AddressUpdate(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}

// DeleteAddressHandler 删除地址
func DeleteAddressHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.AddressDeleteReq
		if err := c.ShouldBindUri(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetAddressSrv()
		resp, err := l.AddressDelete(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}
